﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Socket
        /// </summary>
        Socket socket;
        /// <summary>
        /// 记录通信用的Socket
        /// </summary>
        Dictionary<string, Socket> dic = new Dictionary<string, Socket>();



        /// <summary>
        /// LODE
        /// </summary>
        private void Form1_Load(object sender, EventArgs e)
        {

            string ip = ReaderWriter.ReadIni("config", "server", "ip");
            string port = ReaderWriter.ReadIni("config", "server", "port");
            if (string.IsNullOrEmpty(ip))
            {
                MessageBox.Show("请设置服务器IP地址！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(port))
            {
                MessageBox.Show("请设置服务器端口！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            BaseClass.IpPortIsNull = true;
            BaseClass.ServerIp = ip;
            BaseClass.ServerPort = int.Parse(port);
            

            BaseEvent.PrintFormEvent += BaseEvent_PrintFormEvent;                       //打印消息监听事件
            BaseEvent.ConnectionCountFormEvent += BaseEvent_ConnectionCountFormEvent;   //统计连接数
        }


        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        private void Listen(string t_ip, int t_port) 
        {
            IPAddress ip = IPAddress.Parse(t_ip);           //IP
            IPEndPoint port = new IPEndPoint(ip, t_port);   //端口号

            //创建监听用的Socket
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Bind(port);
                socket.Listen(10);
                BaseEvent.Print("服务器开始监听，IP：" + t_ip + "端口：" + t_port);

                Thread thread = new Thread(AcceptInfo);
                thread.IsBackground = true;
                thread.Start(socket);
            }
            catch (Exception ex)
            {
                BaseEvent.Print(ex.ToString());
                return;
            }
        }



        /// <summary>
        /// 为每个客户端创建一个连接线程
        /// </summary>
        /// <param name="o"></param>
        void AcceptInfo(object o)
        {
            Socket socket = o as Socket;
            while (true)
            {
                try
                {
                    //创建客户端连接
                    Socket tSocket = socket.Accept();
                    string point = tSocket.RemoteEndPoint.ToString();
                    BaseEvent.Print(point + "连接成功！");
                    BaseEvent.ConnectionCount(true);

                    dic.Add(point, tSocket);

                    //为每个客户端创建一个接收线程
                    Thread thReceve = new Thread(ReceiveMsg);
                    thReceve.IsBackground = true;
                    thReceve.Start(tSocket);

                }
                catch (Exception ex)
                {
                    BaseEvent.Print(ex.Message);
                    return;
                }
            }
            
        }


        /// <summary>
        /// 接收线程
        /// </summary>
        /// <param name="o"></param>
        void ReceiveMsg(object o)
        {
            Socket client = o as Socket;
            string point = "";
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024];  ////定义byte数组存放从客户端接收过来的数据

                    bool clientStat = client.Poll(1000, SelectMode.SelectRead); //判断client状态 true已经断开
                    if (!clientStat)
                    {
                        int n = client.Receive(buffer);         //将接收过来的数据放到buffer中，并返回实际接受数据的长度

                        if (n <= 0)
                            return;

                        point = client.RemoteEndPoint.ToString();

                        string words = Encoding.UTF8.GetString(buffer, 0, n);
                        BaseEvent.Print(point + " :> " + words);


                        byte[] s_byte = System.Text.Encoding.GetEncoding("GB2312").GetBytes("您好" + point);
                        client.Send(s_byte);
                    }
                    else
                    {
                        BaseEvent.Print("客户端：" + client.RemoteEndPoint.ToString() + "已经断开");
                        BaseEvent.ConnectionCount(false);
                        dic.Remove(point);
                        client.Close();
                    }

                }
                catch (Exception ex)
                {
                }
            }
            
        }


        /// <summary>
        /// 打印消息实现
        /// </summary>
        /// <param name="meg">消息</param>
        void BaseEvent_PrintFormEvent(string meg)
        {
            this.Invoke((EventHandler)delegate 
            {
                this.txtReceive.Text += "\r\n" + meg;
            });

        }


        /// <summary>
        /// 统计连接数
        /// </summary>
        /// <param name="flag"></param>
        void BaseEvent_ConnectionCountFormEvent(bool flag)
        {
            int count = int.Parse(this.lblConnctionCount.Text.Split('：')[1]);
            if (flag)
            {
                this.Invoke((EventHandler)delegate { this.lblConnctionCount.Text = "当前连接数：" + (count + 1); });
            }
            else
            {
                this.Invoke((EventHandler)delegate { this.lblConnctionCount.Text = "当前连接数：" + (count - 1); });
            }
        }



        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void benSend_Click(object sender, EventArgs e)
        {
            
        }



        /// <summary>
        /// 启动
        /// </summary>
        private void btnStart_Click(object sender, EventArgs e)
        {
            //开始Socket监听
            if (BaseClass.IpPortIsNull)
            {
                Listen(BaseClass.ServerIp, BaseClass.ServerPort);  
                BaseClass.ServerConnt = true;
                btnStart.Enabled = false;
                BaseClass.StartTime = DateTime.Now;
            }
            else
            {
                MessageBox.Show("服务器IP或者端口未设置，请设置后在启动！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        /// 停止
        /// </summary>
        private void btnStop_Click(object sender, EventArgs e)
        {
            //停止监听
            foreach (var item in dic)
            {
                Socket sk = dic[item.Key] as Socket;
                sk.Close();
                BaseEvent.ConnectionCount(false);
            }
            dic.Clear();
            BaseClass.ServerConnt = false;
            this.btnStart.Enabled = true;
        }

        /// <summary>
        /// 设置
        /// </summary>
        private void btnSeting_Click(object sender, EventArgs e)
        {
            frmSet frmst = new frmSet();
            frmst.ShowDialog();
        }



        /// <summary>
        /// 查看状态
        /// </summary>
        private void btnStatus_Click(object sender, EventArgs e)
        {
            frmStatus frmss = new frmStatus();
            frmss.D_Client = dic.Count();
            frmss.ShowDialog();
        }


        /// <summary>
        /// 查看日志
        /// </summary>
        private void btnLog_See_Click(object sender, EventArgs e)
        {

        }


        /// <summary>
        /// 设置日志生成
        /// </summary>
        private void btnLog_Set_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 清空日志
        /// </summary>
        private void btnLog_Clear_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 删除历史日志
        /// </summary>
        private void btnLog_Dele_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 工具
        /// </summary> 
        private void btnTools_Click(object sender, EventArgs e)
        {
            frmTools frmts = new frmTools();
            frmts.ds = dic;
            frmts.ShowDialog();
        }


        

        







    }
}
